import { CheckUtil } from '/@/lib/check';
import { NumberUtil } from '/@/lib/number';
import { TOKEN_VALUE } from '../constants/keys';
import { message } from 'ant-design-vue';

export const ApiUtil = {
  getTotalDataParamsWithToken() {
    return {
      oauth: TOKEN_VALUE,
      pageIndex: 1,
      pageSize: NumberUtil.MAX_PAGE_SIZE,
    };
  },
  getTotalDataParams() {
    return {
      pageIndex: 1,
      pageSize: NumberUtil.MAX_PAGE_SIZE,
    };
  },

  /**
   * 接口返回是否成功
   * @param data
   * @returns {boolean}
   */
  isResponseSuccess(data) {
    if (!CheckUtil.isPlainObject(data)) {
      return false;
    }
    return data.code === 1;
  },

  /**
   * 提交接口返回情况，需要 element-ui 环境
   * @param data
   * @param msg
   */
  showMsg(data, msg) {
    const isResponseSuccess = this.isResponseSuccess(data);
    if (isResponseSuccess) {
      message.success(data.msg || `${msg}成功`);
    } else {
      message.error(data.msg || `${msg}失败`);
    }
  },

  /**
   * get 接口数据清洗
   * @param res
   * @param data
   * @param showMsgFlag
   * @param msg
   * @returns {{res: *, item: (*), data: *}}
   */
  cleanGet({ res, data }, showMsgFlag = false, msg = '获取') {
    const isResponseSuccess = this.isResponseSuccess(data);
    if (showMsgFlag) {
      this.showMsg(data, msg);
    }
    return {
      res,
      data,
      item: isResponseSuccess ? data.data : Object.create(null),
    };
  },

  /**
   * list 接口数据清洗
   * @param res
   * @param data
   * @param showMsgFlag
   * @param msg
   * @returns {{res: *, data: *, pageIndex: number, count: number, list: []}}
   */
  cleanList({ res, data }, showMsgFlag = false, msg = '查询') {
    const isResponseSuccess = this.isResponseSuccess(data);
    let list = [];
    let pageIndex = 1;
    let count = 0;
    if (isResponseSuccess) {
      list = data.data.data;
      pageIndex = data.data.currentPage;
      count = data.data.count;
    }
    if (showMsgFlag) {
      this.showMsg(data, msg);
    }
    return {
      res,
      data,
      list,
      pageIndex,
      count,
    };
  },

  /**
   * insert|update|delete 接口数据清洗
   * @param res
   * @param data
   * @param showMsgFlag
   * @param msg
   * @returns {{res: *, data: *}}
   */
  cleanHandler({ res, data }, showMsgFlag = true, msg = '操作') {
    if (showMsgFlag) {
      this.showMsg(data, msg);
    }
    return { res, data };
  },
};
